<template>
  <div class="subtitle-management-container">
    <div class="tab-header-container">
      <el-tabs v-model="activeTab" class="subtitle-tabs" type="border-card">
        <el-tab-pane label="字幕请求" name="request">
          <SubtitleRequestTab
            :selected-drama="selectedDrama"
            :episodes="episodes"
            :loading-episodes="loadingEpisodes"
            :available-languages="availableLanguages"
            :model-selected-episode="selectedEpisode"
            :model-selected-episodes-from-table="selectedEpisodesFromTable"
            :model-subtitle-form="subtitleForm"
            @drama-selected="handleDramaSelectionInternal"
            @fetch-episodes="fetchEpisodesForDrama"
            @update:modelSelectedEpisode="handleSelectedEpisodeUpdate"
            @update:modelSelectedEpisodesFromTable="handleSelectedEpisodesFromTableUpdate"
            @update:modelSubtitleForm="handleSubtitleFormUpdate"
            @reset-form-fields="resetSubtitleFormFieldsAndSelections"
            @request-submitted="handleRequestSubmitted"
            ref="requestTabRef"
          />
        </el-tab-pane>

        <!-- 新的项目状态标签页 -->
        <el-tab-pane label="项目状态" name="status">
          <ProjectStatusTab ref="projectStatusTabRef" />
        </el-tab-pane>

      </el-tabs>
      <!-- 添加刷新按钮 -->
      <el-button 
        type="primary" 
        :icon="Refresh" 
        circle 
        size="small" 
        class="refresh-button" 
        @click="handleManualRefresh"
        :loading="isRefreshing"
        title="刷新数据"
      />
    </div>
    
    <!-- 视频播放对话框保持不变 -->
    <el-dialog 
      v-model="videoDialogVisible" 
      title="视频播放" 
      width="80%" 
      destroy-on-close
      center
    >
      <div class="video-player-container">
        <video 
          controls 
          autoplay 
          class="video-player" 
          :src="currentVideoUrl"
        >
          您的浏览器不支持 HTML5 视频播放。
        </video>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';

// 导入新的和保留的组件
import SubtitleRequestTab from '../components/subtitle_management/SubtitleRequestTab.vue';
import ProjectStatusTab from '../components/subtitle_management/ProjectStatusTab.vue';

// 导入短剧相关的API
import {
  getCountrySelectList,
  getDramaEpisodes,
  type Drama,
  type Episode,
  type LanguageOption,
} from '../api/drama';

// 与SubtitleRequestTab中的SubtitleFormData保持一致
interface SubtitleForm {
  videoId: string;
  videoUrl: string;
  languages: string[];
  sourceLanguage: string;
  srtOutputPath?: string;
  includeSourceLanguage?: boolean;
}

const activeTab = ref('request');
const selectedDrama = ref<Drama | null>(null);

const episodes = ref<Episode[]>([]);
const loadingEpisodes = ref(false);
const selectedEpisode = ref<Episode | null>(null);
const selectedEpisodesFromTable = ref<Episode[]>([]);

const availableLanguages = ref<LanguageOption[]>([]);

// 视频播放相关状态
const videoDialogVisible = ref(false);
const currentVideoUrl = ref(''); // 保留以备将来使用

// 刷新状态
const isRefreshing = ref(false);

const subtitleForm = reactive<SubtitleForm>({
  videoId: '',
  videoUrl: '',
  languages: [],
  sourceLanguage: 'chinese',
  srtOutputPath: '',
  includeSourceLanguage: false
});

// 组件引用
const requestTabRef = ref<InstanceType<typeof SubtitleRequestTab> | null>(null);
const projectStatusTabRef = ref<InstanceType<typeof ProjectStatusTab> | null>(null);

const handleManualRefresh = async () => {
  if (isRefreshing.value) return;

  isRefreshing.value = true;
  try {
    if (activeTab.value === 'request') {
      // 刷新短剧列表
      requestTabRef.value?.refreshDramas();
      // 如果有选中的短剧，刷新其剧集列表
      if (selectedDrama.value) {
        await fetchEpisodesForDrama(selectedDrama.value.id, true);
      }
    } else if (activeTab.value === 'status') {
      // 刷新项目状态
      await projectStatusTabRef.value?.refresh();
    }
    ElMessage.success('数据刷新成功');
  } catch (error) {
    console.error('刷新数据失败:', error);
    ElMessage.error(`数据刷新失败: ${error instanceof Error ? error.message : '未知错误'}`);
  } finally {
    isRefreshing.value = false;
  }
};

const fetchLanguages = async () => {
  try {
    availableLanguages.value = await getCountrySelectList();
  } catch (error) {
    console.error('获取语言列表失败:', error);
    ElMessage.error(`获取语言列表失败: ${error instanceof Error ? error.message : '未知错误'}`);
    // 设置默认语言选项，确保界面可用
    availableLanguages.value = [
      { countryId: 1, countryName: '中文', countryLanguage: 'chinese', status: 1 },
      { countryId: 2, countryName: 'English', countryLanguage: 'english', status: 1 }
    ];
  }
};

const resetSubtitleFormFieldsAndSelections = () => {
  // 重置表单数据
  subtitleForm.videoId = '';
  subtitleForm.videoUrl = '';
  subtitleForm.languages = [];
  subtitleForm.sourceLanguage = 'chinese';
  subtitleForm.srtOutputPath = '';
  subtitleForm.includeSourceLanguage = false;

  // 重置选择状态
  selectedEpisode.value = null;
  selectedEpisodesFromTable.value = [];

  // 通知子组件重置
  requestTabRef.value?.resetForm();
  requestTabRef.value?.clearEpisodeSelection();
};

const fetchEpisodesForDrama = async (dramaId: number, forceRefresh = false) => {
  if (!dramaId) {
    console.warn('fetchEpisodesForDrama: dramaId 为空');
    return;
  }

  // 防止重复请求
  if (loadingEpisodes.value && !forceRefresh) {
    console.log('fetchEpisodesForDrama: 正在加载中，跳过重复请求');
    return;
  }

  loadingEpisodes.value = true;
  episodes.value = [];

  // 非强制刷新时重置表单
  if (!forceRefresh) {
    resetSubtitleFormFieldsAndSelections();
  }

  try {
    episodes.value = await getDramaEpisodes(dramaId);

    // 强制刷新时保持当前选择状态
    if (forceRefresh && selectedEpisode.value) {
      const updatedEpisode = episodes.value.find(ep => ep.episodeId === selectedEpisode.value?.episodeId);
      if (updatedEpisode) {
        selectedEpisode.value = updatedEpisode;
      } else {
        // 如果选中的剧集不再存在，清除选择
        selectedEpisode.value = null;
      }
    }

    if (forceRefresh && selectedEpisodesFromTable.value.length > 0) {
      selectedEpisodesFromTable.value = selectedEpisodesFromTable.value
        .map(selected => {
          const updated = episodes.value.find(ep => ep.episodeId === selected.episodeId);
          return updated || selected;
        })
        .filter(episode => episodes.value.some(ep => ep.episodeId === episode.episodeId));
    }
  } catch (error) {
    console.error('获取剧集列表失败:', error);
    ElMessage.error(`获取剧集列表失败: ${error instanceof Error ? error.message : '未知错误'}`);
    episodes.value = [];
  } finally {
    loadingEpisodes.value = false;
  }
};

const handleDramaSelectionInternal = (drama: Drama | null) => {
  selectedDrama.value = drama;
  episodes.value = [];

  if (drama) {
    fetchEpisodesForDrama(drama.id);
  } else {
    resetSubtitleFormFieldsAndSelections();
  }
};

const handleSelectedEpisodeUpdate = (episode: Episode | null) => {
  selectedEpisode.value = episode;
};

const handleSelectedEpisodesFromTableUpdate = (episodesList: Episode[]) => {
  selectedEpisodesFromTable.value = episodesList;
};

const handleSubtitleFormUpdate = (form: SubtitleForm) => {
  // 安全地更新表单数据，确保类型一致
  Object.assign(subtitleForm, {
    videoId: form.videoId || '',
    videoUrl: form.videoUrl || '',
    languages: Array.isArray(form.languages) ? form.languages : [],
    sourceLanguage: form.sourceLanguage || 'chinese',
    srtOutputPath: form.srtOutputPath || '',
    includeSourceLanguage: form.includeSourceLanguage || false
  });
};

// 处理请求提交成功事件
const handleRequestSubmitted = () => {
  // 切换到项目状态标签页
  activeTab.value = 'status';

  // 延迟刷新以确保后端数据已更新
  setTimeout(async () => {
    try {
      await projectStatusTabRef.value?.refresh();
    } catch (error) {
      console.error('刷新项目状态失败:', error);
      // 不显示错误消息，因为这是后台操作
    }
  }, 500);
};

onMounted(async () => {
  try {
    await fetchLanguages();
  } catch (error) {
    console.error('组件初始化失败:', error);
  }
});

// 监听标签页切换
watch(activeTab, async (newTab) => {
  if (newTab === 'status') {
    try {
      await projectStatusTabRef.value?.refresh();
    } catch (error) {
      console.error('切换到项目状态页面时刷新失败:', error);
    }
  }
});
</script>

<style scoped>
.subtitle-management-container {
  padding: 15px;
}
.tab-header-container {
  position: relative;
}
.refresh-button {
  position: absolute;
  top: 8px;
  right: 15px;
  z-index: 10;
}
.video-player-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #000;
}
.video-player {
  max-width: 100%;
  max-height: 70vh;
}
</style> 